﻿using System;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
using ServBus.ListForm2013.License;
using ServBus.ListForm2013.Utility;

namespace ServBus.ListForm2013.TimerJob
{
    public class SyncActivationJob : SPJobDefinition
    {
        internal static readonly string JOB_NAME = "InfoBus ListForm 2013 Sync Activation";

        public SyncActivationJob()
        {
        }

        public SyncActivationJob(SPWebApplication webapp)
            : base(JOB_NAME, webapp, null, SPJobLockType.Job)
        {
            base.Title = JOB_NAME;
        }

        public SyncActivationJob(string jobName, SPService service, SPServer server, SPJobLockType lockType)
            : base(jobName, service, server, lockType)
        {
            base.Title = JOB_NAME;
        }

        public override void Execute(Guid targetInstanceId)
        {
            try
            {
                Activations.SyncFromWebApps();
            }
            catch (Exception ex)
            {
                ErrorLog.Write(ex.Message + "\r\n" + ex.StackTrace, System.Diagnostics.EventLogEntryType.Error);
            }
        }

        public static void InstallToWebapp(SPWebApplication webapp)
        {
            // Remove first
            RemoveFromWebapp(webapp);

            // Then, install
            SyncActivationJob job = new SyncActivationJob(webapp);
            SPMinuteSchedule schedule = new SPMinuteSchedule();
            schedule.BeginSecond = 0;
            schedule.EndSecond = 59;
            schedule.Interval = 5;
            job.Schedule = schedule;
            job.Update();
        }

        public static void RemoveFromWebapp(SPWebApplication webapp)
        {
            foreach (SPJobDefinition job in webapp.JobDefinitions)
            {
                if (job.Name == JOB_NAME)
                {
                    job.Delete();
                    break;
                }
            }
        }
    }
}
